import { Hono } from "hono";
import { z } from "zod";
import validator from "../middlewares/validate";
import { MemoService } from "../services/memo";
import Responder from "../middlewares/response";
import { authMiddleware } from "../middlewares/auth";

const memo = new Hono();
const memoService = new MemoService();

memo.use("*", authMiddleware);

const createMemoSchema = z.object({
  content: z.string().min(1, "内容不能为空"),
  mood: z.object({
    level: z.number().min(1).max(5)
  }).optional()
});

const updateMemoSchema = z.object({
  content: z.string().min(1, "内容不能为空").optional(),
  mood: z.object({
    level: z.number().min(1).max(5)
  }).optional()
});

// 获取所有笔记
memo.get("/", async (c) => {
  const userId = c.get("userId");
  const memos = await memoService.getMemos(userId);
  return Responder.success().setData(memos).build(c);
});

// 创建笔记
memo.post("/", validator("json", createMemoSchema), async (c) => {
  const userId = c.get("userId");
  const data = c.req.valid("json");
  
  const memo = await memoService.createMemo({
    userId,
    ...data
  });

  return Responder.success("笔记创建成功").setData(memo).build(c);
});

// 更新笔记
memo.put("/:id", validator("json", updateMemoSchema), async (c) => {
  const userId = c.get("userId");
  const memoId = c.req.param("id");
  const data = c.req.valid("json");

  const memo = await memoService.updateMemo(userId, memoId, data);
  return Responder.success("笔记更新成功").setData(memo).build(c);
});

// 删除笔记
memo.delete("/:id", async (c) => {
  const userId = c.get("userId");
  const memoId = c.req.param("id");

  await memoService.deleteMemo(userId, memoId);
  return Responder.success("笔记删除成功").build(c);
});

export default memo;
